import re
import sys
from typing import Dict

import networkx as nx
import matplotlib.pyplot as plt
import json


class Node:

    def __init__(self,id:int,value:str,son:[int]):
        self.id = id
        self.son = son
        self.value = value
        self.alias = ""
        self.exp = ""

    def __str__(self):
        return str(self.id)+str(self.value)+str(self.son)


def parse(plan:[str])->Dict[int,Node]:
    nodes = {}  # id -> node
    for a in plan:
        x = a.find("[")
        print(a,x)
        if x<0:
            continue
        a = a[6:x].strip()
        print(a+"|")
        b = a.split(" ")
       # print(b)
        id = int(b[0].replace('(','').replace(')',''))
        b.pop(0)
        son = []
        if b[-1].startswith('('):
            son = list(map(int,b[-1].replace('(','').replace(')','').split(',')))
            b.pop()
        c = " ".join(b)
        # print(id,c,son)
        nodes[id] = Node(id,c,son)
    return nodes

def flush(nodes:Dict[int,Node]):
    for id,node in nodes.items():
        # print(i,j)
        if node.alias!="":
            node.exp = node.alias
        else:
            value:str = node.value
            if (value.startswith("TR")):
                node.exp = value.split(" ")[-1]
            elif (value.startswith("TW")):
                node.exp = value.split(" ")[-1]+":=" + nodes[node.son[0]].exp
            elif  (value=="r(t)" or value == "r(r')"):
                node.exp = "t("+ nodes[node.son[0]].exp+")"
            elif (value=="ba(+*)"):
                if (len(node.son))>=2:
                    node.exp =  nodes[node.son[0]].exp + "%*%" + nodes[node.son[1]].exp
                elif (len(node.son))>=1:
                    node.exp = "{%*%,(" +nodes[node.son[0]].exp +")}"
                else:
                    node.exp = "%*%"
            elif (value.startswith("b(")):
                op = value[2:3]
                # print("op="+op)
                if (len(node.son)) >= 2:
                    node.exp = nodes[node.son[0]].exp + op + nodes[node.son[1]].exp
                elif (len(node.son)) >= 1:
                    node.exp = "{"+op+",(" + nodes[node.son[0]].exp + ")}"
                else:
                    node.exp = op
            else:
                node.exp = value

def explain(nodes:Dict[int,Node]):
    for id, node in nodes.items():
        print(id,node.son, node.exp)

def alias(nodes:Dict[int,Node],id:int,name:str):
    nodes[id].alias = name

def load(filename:str)->Dict[int,Node]:
    with open(filename,"r") as f:
        plan = f.readlines()
        return parse(plan)

def load_alias(nodes:Dict[int,Node],filename:str):
    with open(filename, "r") as f:
        for line in f.readlines():
            arr = line.replace("\n","").split(" ")
            if (len(arr)>=2):
                id = int(arr[0])
                name = arr[1]
                alias(nodes,id,name)

if __name__ == '__main__':
    nodes = {}
    while True:
        cmd = input("command: ")
        if cmd=="l":
            filename = input("filename: ")
            nodes = load(filename)
        elif cmd=="la":
            filename = input("filename: ")
            load_alias(nodes,filename)
        elif cmd == "p":
            flush(nodes)
            explain(nodes)
        elif cmd == "a":
            id = int(input("id: "))
            name = input("name: ")
            alias(nodes, id, name)
        elif cmd == "q":
            break
